package com.csl.ams.nike_mvp.utils


import CONSUMABLES_RECEIVE
import CONSUMABLES_RESTOCK
import CONSUMABLES_WAREHOUSE
import android.app.Activity
import android.content.Context
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.support.v4.content.ContextCompat
import android.support.v7.widget.AppCompatCheckBox
import android.support.v7.widget.AppCompatEditText
import android.support.v7.widget.AppCompatImageView
import android.support.v7.widget.AppCompatSpinner
import android.support.v7.widget.AppCompatTextView
import android.util.Log
import android.view.Gravity
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.ArrayAdapter
import android.widget.CompoundButton
import android.widget.FrameLayout
import android.widget.ListPopupWindow
import android.widget.PopupWindow
import android.widget.Spinner
import android.widget.TextView
import com.spit.tph.R
import com.spit.tph.nike_mvp.utils.ScreenUtils
import com.spit.tph.nike_mvp.utils.ToastUtil
import com.yyc.stocktake.bean.DataBean
import java.lang.reflect.Field;


/**
 * User: Nike
 *  2024/1/17 10:45
 */
class PopupWindowTool(private val context: Activity) {

    private var pop: PopupWindow? = null

    var status = 0

    fun showPop() {
        if (pop != null && pop!!.isShowing) {
            pop!!.dismiss()
        }
        pop = PopupWindow(context)
        val popView = LayoutInflater.from(context).inflate(R.layout.p_edit, null, false)
        pop?.setContentView(popView);
        var width = ScreenUtils.getWidth(context);
//        pop?.setWidth(width * 3 / 4);
        pop?.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        pop?.setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
//        pop?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT));
        pop?.setFocusable(true);
        pop?.setOutsideTouchable(true);
        //点击其他地方消失
        popView.setOnTouchListener { v, event ->
            closePopupWindow()
            false
        }

        val etRemark = popView.findViewById<AppCompatEditText>(R.id.et_remark)
        //居中显示，第一个参数的控件只要是这个popwindow里面的随便一个控件就行
        pop?.showAtLocation(etRemark, Gravity.BOTTOM, 0, 0);
        val ivNormal = popView.findViewById<AppCompatImageView>(R.id.iv_normal)
        val ivRepair = popView.findViewById<AppCompatImageView>(R.id.iv_repair)
        //根据控件定点显示，后面的两个参数是偏移量
//        pop?.showAtLocation(etRemark, Gravity.CENTER, 0, 0)
        //设置默认状态
        ivNormal.background = ContextCompat.getDrawable(context, R.drawable.icon_1)
        ivRepair.background = ContextCompat.getDrawable(context, R.drawable.icon_2)
        popView.findViewById<View>(R.id.ly_normal).setOnClickListener {
            status = 0
            ivNormal.background = ContextCompat.getDrawable(context, R.drawable.icon_1)
            ivRepair.background = ContextCompat.getDrawable(context, R.drawable.icon_2)
        }

        popView.findViewById<View>(R.id.ly_repair).setOnClickListener {
            status = 1
            ivRepair.background = ContextCompat.getDrawable(context, R.drawable.icon_1)
            ivNormal.background = ContextCompat.getDrawable(context, R.drawable.icon_2)
        }

        popView.findViewById<AppCompatTextView>(R.id.tv_cancel).setOnClickListener {
            closePopupWindow()
        }
        popView.findViewById<AppCompatTextView>(R.id.tv_submit).setOnClickListener {
            val s = etRemark.text.toString()
//            mListener?.onText(status, s)
            closePopupWindow()
        }
    }

    /**
     * 关闭窗口
     */
    private fun closePopupWindow() {
        if (pop != null && pop?.isShowing == true) {
            pop?.dismiss()
            pop = null
//            hideSoftKeyboard()
        }
    }

    private fun hideSoftKeyboard() {
        val inputMethodManager = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        inputMethodManager.hideSoftInputFromWindow(context.window.decorView.windowToken, 0)
    }


    /*private var mListener: OnClickListener? = null

    fun setOnClickListener(l: OnClickListener) {
        mListener = l
    }

    interface OnClickListener {
        fun onText(status: Int, text: String)
    }*/

    fun showBottom() {
        // 加载弹窗布局
        var pwView = LayoutInflater.from(context).inflate(R.layout.p_b_select, null, false)
        // 实例化 PopupWindow
        pop = PopupWindow(
            pwView,
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT
        )
        pop?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT));
        // 设置 popupWindow
//        pop?.isOutsideTouchable = true
//        pop?.isTouchable = true
//        pop?.isFocusable = true
        // 加载弹窗动画
        pop?.animationStyle = R.style.pw_bottom_anim_style
        // 设置弹窗关闭监听——恢复亮度
        pop?.setOnDismissListener {
            backgroundAlpha(1f)
        }
        pop?.showAtLocation(pwView, Gravity.BOTTOM, 0, 0)

        pwView.findViewById<FrameLayout>(R.id.fy_close).setOnClickListener {
            mListener?.onClose()
            closePopupWindow()
        }

        pwView.findViewById<AppCompatCheckBox>(R.id.cb_text)
            .setOnCheckedChangeListener { compoundButton, b ->
                mListener?.onCheckedChangeListener(compoundButton, b)
            }


        pwView.findViewById<AppCompatTextView>(R.id.bt_receive).setOnClickListener {
            mListener?.onReceive()
            closePopupWindow()
        }
        pwView.findViewById<AppCompatTextView>(R.id.bt_warehouse).setOnClickListener {
            mListener?.onWarehouse()
            closePopupWindow()
        }
    }

    // 控制背景亮度
    fun backgroundAlpha(bgAlpha: Float) {
        val lp = context.window.attributes
        lp.alpha = bgAlpha //0.0-1.0
        context.window.attributes = lp
    }

    private var mListener: OnClickListener? = null

    fun setOnClickListener(l: OnClickListener) {
        mListener = l
    }

    interface OnClickListener {
        fun onClose()
        fun onReceive()
        fun onWarehouse()
        fun onCheckedChangeListener(var1: CompoundButton, var2: Boolean)

    }


    fun showConsumablesStatus() {
        var pwView = LayoutInflater.from(context).inflate(R.layout.p_c_status, null, false)
        pop = PopupWindow(
            pwView,
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT
        )
        pop?.setBackgroundDrawable(ColorDrawable(-0x80000000))
        pop?.setAnimationStyle(R.style.PopupAnimation);
        pop?.isOutsideTouchable = true
        pop?.isTouchable = true
        pop?.isFocusable = true
        pop?.setOnDismissListener {
            backgroundAlpha(1f)
        }
        pop?.showAtLocation(pwView, Gravity.CENTER, 0, 0)
        pwView.findViewById<FrameLayout>(R.id.fy_close).setOnClickListener {
            closePopupWindow()
        }
        pwView.findViewById<FrameLayout>(R.id.layout).setOnClickListener {
//            closePopupWindow()
        }
        pwView.findViewById<AppCompatTextView>(R.id.bt_receive).setOnClickListener {
            closePopupWindow()
            mListener1?.onStatus(CONSUMABLES_RECEIVE)
        }
        pwView.findViewById<AppCompatTextView>(R.id.bt_warehouse).setOnClickListener {
            closePopupWindow()
            mListener1?.onStatus(CONSUMABLES_WAREHOUSE)
        }
        pwView.findViewById<AppCompatTextView>(R.id.bt_restock).setOnClickListener {
            closePopupWindow()
            mListener1?.onStatus(CONSUMABLES_RESTOCK)
        }
        pwView?.isFocusable = false
        pwView?.isFocusableInTouchMode = true
        pwView?.setOnKeyListener { _, keyCode, _ ->
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                // 返回键被点击，这里可以做你想要的处理，比如不做任何操作或者提示用户
                return@setOnKeyListener true // 拦截返回键事件，不传递给系统
            }
            false
        }
    }

    private var mListener1: OnClickListener1? = null

    fun setOnClickListener1(l: OnClickListener1) {
        mListener1 = l
    }

    interface OnClickListener1 {
        fun onStatus(i: Int)
    }

    //入库
    fun showWarehouse(list1: ArrayList<DataBean>) {
        var pwView = LayoutInflater.from(context).inflate(R.layout.p_receive, null, false)
        pop = PopupWindow(
            pwView,
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT
        )
        pop?.setBackgroundDrawable(ColorDrawable(-0x80000000))
        pop?.setAnimationStyle(R.style.PopupAnimation);
        pop?.isOutsideTouchable = true
        pop?.isTouchable = true
        pop?.isFocusable = true
        pop?.setOnDismissListener {
            backgroundAlpha(1f)
        }
        pop?.showAtLocation(pwView, Gravity.CENTER, 0, 0)
        val spReceive = pwView.findViewById<AppCompatSpinner>(R.id.sp_receive)
        val bean = DataBean()
        bean.dataName = context.getString(R.string.text3)
        var list = ArrayList<DataBean>()
        list.addAll(list1)
        list.add(bean)
        val adpter = CustomSpinnerAdapter(context, list)
        spReceive.adapter = adpter
        spReceive.setSelection(list.size - 1)

        if (list.size > 20) {
            try {
                val popup: Field = Spinner::class.java.getDeclaredField("mPopup")
                popup.isAccessible = true
                val popupWindow = popup.get(spReceive) as ListPopupWindow
                popupWindow.height = 500
            } catch (e: Exception) {
                Log.e("spinner", e.toString())
            }
        }

        pwView.findViewById<AppCompatTextView>(R.id.tv_cancel).setOnClickListener {
            closePopupWindow()
        }
        pwView.findViewById<AppCompatTextView>(R.id.tv_submit).setOnClickListener {
            if (spReceive.selectedItemPosition == list.size - 1){
                ToastUtil.showShortToast(context.getString(R.string.text3))
                return@setOnClickListener
            }
            mListener2?.onReceiveCallback(list[spReceive.selectedItemPosition])
            closePopupWindow()
        }
    }

    //领用1
    fun showReceive(list1: ArrayList<DataBean>){
        var pwView = LayoutInflater.from(context).inflate(R.layout.p_warehouse, null, false)
        pop = PopupWindow(
            pwView,
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT
        )
        pop?.setBackgroundDrawable(ColorDrawable(-0x80000000))
        pop?.setAnimationStyle(R.style.PopupAnimation);
        pop?.isOutsideTouchable = true
        pop?.isTouchable = true
        pop?.isFocusable = true
        pop?.setOnDismissListener {
            backgroundAlpha(1f)
        }
        pop?.showAtLocation(pwView, Gravity.CENTER, 0, 0)

    }

    //领用
    fun showReceive(list1: ArrayList<DataBean>, list2: ArrayList<DataBean>) {
        var pwView = LayoutInflater.from(context).inflate(R.layout.p_warehouse, null, false)
        pop = PopupWindow(
            pwView,
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT
        )
        pop?.setBackgroundDrawable(ColorDrawable(-0x80000000))
        pop?.setAnimationStyle(R.style.PopupAnimation);
        pop?.isOutsideTouchable = true
        pop?.isTouchable = true
        pop?.isFocusable = true
        pop?.setOnDismissListener {
            backgroundAlpha(1f)
        }
        pop?.showAtLocation(pwView, Gravity.CENTER, 0, 0)

        val etText = pwView.findViewById<AppCompatEditText>(R.id.et_text)

        val spReceive = pwView.findViewById<AppCompatSpinner>(R.id.sp_receive)
        val bean = DataBean()
        bean.dataName = context.getString(R.string.text4)
        var list = ArrayList<DataBean>()
        list.addAll(list1)
        list.add(bean)
        val adpter = CustomSpinnerAdapter(context, list)
        spReceive.adapter = adpter
        spReceive.setSelection(list.size - 1)
        if (list.size > 20) {
            try {
                val popup: Field = Spinner::class.java.getDeclaredField("mPopup")
                popup.isAccessible = true
                val popupWindow = popup.get(spReceive) as ListPopupWindow
                popupWindow.height = 500
            } catch (e: Exception) {
                Log.e("spinner", e.toString())
            }
        }

        pwView.findViewById<FrameLayout>(R.id.fy_restock).visibility = View.VISIBLE
        val spRestock = pwView.findViewById<AppCompatSpinner>(R.id.sp_restock)
        val bean1 = DataBean()
        bean1.dataName = context.getString(R.string.text5)
        var listMaterialBean = ArrayList<DataBean>()
        listMaterialBean.addAll(list2)
        listMaterialBean.add(bean1)
        val adpter2 = CustomSpinnerAdapter(context, listMaterialBean)
        spRestock.adapter = adpter2
        spRestock.setSelection(listMaterialBean.size - 1)
        if (listMaterialBean.size > 20) {
            try {
                val popup: Field = Spinner::class.java.getDeclaredField("mPopup")
                popup.isAccessible = true
                val popupWindow = popup.get(spRestock) as ListPopupWindow
                popupWindow.height = 500
            } catch (e: Exception) {
                Log.e("spinner", e.toString())
            }
        }

        pwView.findViewById<AppCompatTextView>(R.id.tv_cancel).setOnClickListener {
            closePopupWindow()
        }
        pwView.findViewById<FrameLayout>(R.id.scan).setOnClickListener {
            mListener2?.onWarehouseScanCallback(etText)
        }
        pwView.findViewById<AppCompatTextView>(R.id.tv_submit).setOnClickListener {
            val s = etText.text.toString()
            if (s.isEmpty()){
                ToastUtil.showShortToast(context.getString(R.string.text6))
                return@setOnClickListener
            }
            if (spRestock.selectedItemPosition == listMaterialBean.size - 1){
                ToastUtil.showShortToast( context.getString(R.string.text5))
                return@setOnClickListener
            }
            val materialBean = listMaterialBean[spRestock.selectedItemPosition]
            val bean = list[spReceive.selectedItemPosition]
            mListener2?.onWarehouseCallback(if (spReceive.selectedItemPosition == list.size - 1) null else bean, s, materialBean)
            closePopupWindow()
        }
    }

    //补货
    fun showRestock(listWarehouseBean1: ArrayList<DataBean>, listMaterialBean2: ArrayList<DataBean>) {
        var pwView = LayoutInflater.from(context).inflate(R.layout.p_receive, null, false)
        pop = PopupWindow(
            pwView,
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT
        )
        pop?.setBackgroundDrawable(ColorDrawable(-0x80000000))
        pop?.setAnimationStyle(R.style.PopupAnimation);
        pop?.isOutsideTouchable = true
        pop?.isTouchable = true
        pop?.isFocusable = true
        pop?.setOnDismissListener {
            backgroundAlpha(1f)
        }
        pop?.showAtLocation(pwView, Gravity.CENTER, 0, 0)

        val spReceive = pwView.findViewById<AppCompatSpinner>(R.id.sp_receive)
        val bean = DataBean()
        bean.dataName = context.getString(R.string.text3)
        var listWarehouseBean = ArrayList<DataBean>()
        listWarehouseBean.addAll(listWarehouseBean1)
        listWarehouseBean.add(bean)
        val adpter = CustomSpinnerAdapter(context, listWarehouseBean)
        spReceive.adapter = adpter
        spReceive.setSelection(listWarehouseBean.size - 1)
        if (listWarehouseBean.size > 20) {
            try {
                val popup: Field = Spinner::class.java.getDeclaredField("mPopup")
                popup.isAccessible = true
                val popupWindow = popup.get(spReceive) as ListPopupWindow
                popupWindow.height = 500
            } catch (e: Exception) {
                Log.e("spinner", e.toString())
            }
        }

        pwView.findViewById<FrameLayout>(R.id.fy_restock).visibility = View.VISIBLE
        val spRestock = pwView.findViewById<AppCompatSpinner>(R.id.sp_restock)
        val bean1 = DataBean()
        bean1.dataName = context.getString(R.string.text5)
        var listMaterialBean = ArrayList<DataBean>()
        listMaterialBean.addAll(listMaterialBean2)
        listMaterialBean.add(bean1)
        val adpter2 = CustomSpinnerAdapter(context, listMaterialBean)
        spRestock.adapter = adpter2
        spRestock.setSelection(listMaterialBean.size - 1)
        if (listMaterialBean.size > 20) {
            try {
                val popup: Field = Spinner::class.java.getDeclaredField("mPopup")
                popup.isAccessible = true
                val popupWindow = popup.get(spRestock) as ListPopupWindow
                popupWindow.height = 500
            } catch (e: Exception) {
                Log.e("spinner", e.toString())
            }
        }

        pwView.findViewById<AppCompatTextView>(R.id.tv_cancel).setOnClickListener {
            closePopupWindow()
        }
        pwView.findViewById<AppCompatTextView>(R.id.tv_submit).setOnClickListener {
            if (spReceive.selectedItemPosition == listWarehouseBean.size - 1){
                ToastUtil.showShortToast( context.getString(R.string.text3))
                return@setOnClickListener
            }
            if (spRestock.selectedItemPosition == listMaterialBean.size - 1){
                ToastUtil.showShortToast(context.getString(R.string.text5))
                return@setOnClickListener
            }
            mListener2?.onRestockCallback(listWarehouseBean[spReceive.selectedItemPosition], listMaterialBean[spRestock.selectedItemPosition])
            closePopupWindow()
        }
    }

    private var mListener2: OnClickListener2? = null

    fun setOnClickListener2(l: OnClickListener2) {
        mListener2 = l
    }

    interface OnClickListener2 {
        fun onWarehouseCallback(bean: DataBean?, s: String, materialBean: DataBean)
        fun onReceiveCallback(bean: DataBean)
        fun onRestockCallback(bean: DataBean, dataBean: DataBean)
        fun onWarehouseScanCallback(etText: AppCompatEditText)
    }

    class CustomSpinnerAdapter(context: Context, data: ArrayList<DataBean>) : ArrayAdapter<DataBean>(context, android.R.layout.simple_spinner_item, data) {

        override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
            val view = super.getView(position, convertView, parent)
            val tv = view.findViewById<TextView>(android.R.id.text1)
            tv.text = getItem(position)?.dataName
            return view
        }

        override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup): View {
            val view = super.getDropDownView(position, convertView, parent)
            val tv = view.findViewById<TextView>(android.R.id.text1)
            tv.text = getItem(position)?.dataName
            return view
        }
    }

    fun showEditNumber(bean: DataBean, position: Int, mCStatus: Int) {
        var pwView = LayoutInflater.from(context).inflate(R.layout.p_edit_num, null, false)
        pop = PopupWindow(
            pwView,
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT
        )
        pop?.setBackgroundDrawable(ColorDrawable(-0x80000000))
        pop?.setAnimationStyle(R.style.PopupAnimation);
        pop?.isOutsideTouchable = true
        pop?.isTouchable = true
        pop?.isFocusable = true
        pop?.setOnDismissListener {
            backgroundAlpha(1f)
        }
        pop?.showAtLocation(pwView, Gravity.CENTER, 0, 0)

        val tvText1 = pwView.findViewById<AppCompatTextView>(R.id.tv_text1)
        val etNumber = pwView.findViewById<AppCompatEditText>(R.id.et_number)
        etNumber.setText("${bean.num}")
        val unlimited = context.getString(R.string.unlimited)
        when(mCStatus){
            CONSUMABLES_RECEIVE ->{
                val limitedUse = context.getString(R.string.limited_use)
                val currentInventory = context.getString(R.string.current_inventory)
                val text = "$limitedUse: ${if (bean.singleClaimLimit == 0) unlimited else bean.singleClaimLimit}\n$currentInventory: ${bean.currentInventory}"
                tvText1.text = text
            }
            CONSUMABLES_WAREHOUSE ->{
                tvText1.text = "${context.getString(R.string.text15)}：" + if (bean.inventoryUpper == 0) unlimited else bean.inventoryUpper
            }
            CONSUMABLES_RESTOCK ->{
                tvText1.text = "${context.getString(R.string.text16)}：" + bean.currentInventory
            }
        }


        pwView.findViewById<AppCompatTextView>(R.id.tv_cancel).setOnClickListener {
            closePopupWindow()
            hideSoftKeyboard(etNumber)
        }
        pwView.findViewById<AppCompatTextView>(R.id.tv_submit).setOnClickListener {
            val s = etNumber.text.toString()
            val num = s.toInt()
            if (num != null && num > 0) {
                /*when(mCStatus){
                    CONSUMABLES_RECEIVE ->{
                        if ((bean.singleClaimLimit != 0 && num > bean.singleClaimLimit) || (bean.currentInventory != 0 && num > bean.currentInventory)){
                            ToastUtil.showShortToast(context.getString(R.string.text14))
                            return@setOnClickListener
                        }
                    }
                    CONSUMABLES_WAREHOUSE ->{
                        val currentInventory = bean.currentInventory
                        var ci = currentInventory + num
                        if (ci >= bean.inventoryUpper){
//                            ToastUtil.showShortToast(context.getString(R.string.text14))
//                            return@setOnClickListener
                        }
                    }
                    CONSUMABLES_RESTOCK ->{
                        if (num > bean.currentInventory){
                            ToastUtil.showShortToast(context.getString(R.string.text14))
                            return@setOnClickListener
                        }
                    }
                }*/
                bean.num = num
                mListener3?.onEditNumber(bean, position)
                closePopupWindow()
                hideSoftKeyboard(etNumber)
            }
        }
    }

    private fun hideSoftKeyboard(editText: AppCompatEditText) {
        val inputMethodManager = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        inputMethodManager.hideSoftInputFromWindow(editText.windowToken, 0)
    }


    private var mListener3: OnClickListener3? = null

    fun setOnClickListener3(l: OnClickListener3) {
        mListener3 = l
    }

    interface OnClickListener3 {
        fun onEditNumber(bean: DataBean, position: Int)
    }

}

